<template>
  <view class="edit-clothes">
    <view class="form-container">
      <!-- 图片上传 -->
      <view class="image-upload">
        <image 
          :src="formData.image_url" 
          mode="aspectFit" 
          class="preview-image"
        ></image>
 <!--       <button @click="changeImage" class="upload-btn">更换图片</button> -->
      </view>
      
      <!-- 基本信息表单 -->
      <!-- 衣服大类选择器 -->
      <view class="form-item">
        <text class="label">衣服大类:</text>
        <view class="category-select" @tap="openMainCategoryPicker">
          <text>{{ selectedMainCategory || '请选择衣服大类' }}</text>
        </view>
      </view>

      <!-- 详细类别选择器 -->
      <view class="form-item">
        <text class="label">详细类别:</text>
        <view class="category-select" @tap="openSubCategoryPicker" :class="{ 'disabled': !selectedMainCategory }">
          <text>{{ selectedSubCategory || (selectedMainCategory ? '请选择详细类别' : '请先选择衣服大类') }}</text>
        </view>
      </view>
      
      <view class="form-item">
        <text class="label">颜色:</text>
        <input v-model="formData.color" placeholder="输入颜色" />
      </view>
      
      <view class="form-item">
        <text class="label">材质:</text>
        <input v-model="formData.material" placeholder="输入材质" />
      </view>
      
      <view class="form-item">
        <text class="label">尺码:</text>
        <input v-model="formData.size" placeholder="输入尺码" />
      </view>
      
      <view class="form-item">
        <text class="label">版型:</text>
        <input v-model="formData.fit" placeholder="输入版型" />
      </view>
      
      <view class="form-item">
        <text class="label">季节:</text>
        <input v-model="formData.season" placeholder="输入季节" />
      </view>
      
	  <view class="form-item">
	    <text class="label">品牌:</text>
	    <input v-model="formData.brand" placeholder="输入品牌" />
	  </view>
      <!-- 标签管理 -->
      <view class="form-item tags-item">
        <text class="label">标签:</text>
        <view class="tags-container">
          <view
            v-for="(tag, idx) in formData.tags"
            :key="idx"
            class="tag"
          >
            <text>{{ tag }}</text>
            <text class="delete-tag" @tap.stop="deleteTag(idx)">×</text>
          </view>
          <view v-if="!isAddingTag" class="add-tag" @tap.stop="startAddingTag">
            <text>+ 添加标签</text>
          </view>
          <input
            v-if="isAddingTag"
            v-model="newTag"
            placeholder="输入标签(如:休闲/正式)"
            @confirm="addTag"
            @blur="addTag"
            :focus="isAddingTag"
            class="tag-input"
          />
        </view>
      </view>
      
      <!-- 保存按钮 -->
      <button class="save-btn" @click="saveClothesInfo">保存修改</button>
    </view>
    
    <!-- 衣服大类选择弹窗 -->
    <view v-if="showMainCategoryPicker" class="custom-picker">
      <view class="custom-picker-mask" @tap="closeMainCategoryPicker"></view>
      <view class="custom-picker-content">
        <view class="picker-header">
          <text>选择衣服大类</text>
          <text @tap="closeMainCategoryPicker" class="close-btn">×</text>
        </view>
        <scroll-view scroll-y class="picker-options">
          <view 
            v-for="(item, index) in mainCategories" 
            :key="index"
            class="picker-option"
            :class="{ 'selected': selectedMainCategoryIndex === index }"
            @tap="selectMainCategory(index)"
          >
            <text>{{ item }}</text>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 详细类别选择弹窗 -->
    <view v-if="showSubCategoryPicker" class="custom-picker">
      <view class="custom-picker-mask" @tap="closeSubCategoryPicker"></view>
      <view class="custom-picker-content">
        <view class="picker-header">
          <text>选择详细类别</text>
          <text @tap="closeSubCategoryPicker" class="close-btn">×</text>
        </view>
        <scroll-view scroll-y class="picker-options">
          <view 
            v-for="(item, index) in subCategories" 
            :key="index"
            class="picker-option"
            :class="{ 'selected': selectedSubCategoryIndex === index }"
            @tap="selectSubCategory(index)"
          >
            <text>{{ item }}</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import setting from "../../setting"
export default {
  data() {
    return {
      formData: {
        clothes_id: "", // 添加clothes_id字段
        category: "", // 使用category替代mainCategory
        subcategory: "", // 使用subcategory替代subCategory
        color: "",
        material: "",
        size: "",
        fit: "",
        season: "",
        tags: [],
      },
      isAddingTag: false,
      newTag: "",

      // 衣服大类数据
      mainCategories: ["上衣", "裤子", "裙子", "鞋子", "其他"],
      selectedMainCategory: "",
      selectedMainCategoryIndex: -1,
      showMainCategoryPicker: false,

      // 详细类别数据（根据大类动态变化）
      subCategories: [],
      selectedSubCategory: "",
      selectedSubCategoryIndex: -1,
      showSubCategoryPicker: false,

      // 所有详细类别数据
      allSubCategories: {
        上衣: [
          "毛衣",
          "衬衣",
          "短袖",
          "吊带",
          "长袖",
          "外套",
          "西装外套",
          "卫衣",
          "长羽绒服",
          "短羽绒服",
          "大衣",
          "冲锋衣",
        ],
        裤子: ["牛仔裤", "休闲裤", "运动裤", "短裤", "加绒裤", "西裤", "工装裤", "背带裤"],
        裙子: ["连衣裙", "半身裙", "长裙", "短裙", "加绒裙"],
        鞋子: ["运动鞋", "皮鞋", "凉鞋", "雪地靴", "靴子", "板鞋", "布鞋", "高跟鞋", "保暖鞋"],
        其他: ["首饰", "帽子", "围巾", "包包", "墨镜", "领带"],
      },
    }
  },
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on("sendDataToEditPage", (data) => {
      this.formData = {
        ...data,
        tags: [...data.tags], // 深拷贝数组
      }

      // 初始化类别选择
      if (data.category) {
        this.selectedMainCategory = data.category
        this.selectedMainCategoryIndex = this.mainCategories.indexOf(data.category)
        this.subCategories = this.allSubCategories[data.category] || []

        if (data.subcategory) {
          this.selectedSubCategory = data.subcategory
          this.selectedSubCategoryIndex = this.subCategories.indexOf(data.subcategory)
        }
      }
    })
  },

  methods: {
    // 衣服大类相关方法
    openMainCategoryPicker() {
      this.showMainCategoryPicker = true
    },
    closeMainCategoryPicker() {
      this.showMainCategoryPicker = false
    },
    selectMainCategory(index) {
      this.selectedMainCategory = this.mainCategories[index]
      this.selectedMainCategoryIndex = index
      this.formData.category = this.selectedMainCategory // 同步到formData

      // 重置子类选择
      this.selectedSubCategory = ""
      this.formData.subcategory = ""
      this.subCategories = this.allSubCategories[this.selectedMainCategory] || []

      // 关键修复：添加这行关闭弹窗
      this.showMainCategoryPicker = false
    },
    // 详细类别相关方法
    openSubCategoryPicker() {
      if (!this.selectedMainCategory) {
        uni.showToast({ title: "请先选择衣服大类", icon: "none" })
        return
      }
      this.showSubCategoryPicker = true
    },
    closeSubCategoryPicker() {
      this.showSubCategoryPicker = false
    },
    selectSubCategory(index) {
      this.selectedSubCategory = this.subCategories[index]
      this.selectedSubCategoryIndex = index
      this.formData.subcategory = this.selectedSubCategory // 同步到formData

      // 关键修复：添加这行关闭弹窗
      this.showSubCategoryPicker = false
    },

    startAddingTag() {
      this.isAddingTag = true
    },

    // 修改后的添加标签方法
    async addTag() {
      const tag = this.newTag.trim()
      if (!tag) {
        this.isAddingTag = false
        return
      }

      // 检查标签是否已存在
      if (this.formData.tags.includes(tag)) {
        uni.showToast({ title: "标签已存在", icon: "none" })
        this.newTag = ""
        this.isAddingTag = false
        return
      }

      try {
        // 调用后端API添加标签
        const response = await uni.request({
          url: `${setting.url}/api/clothes/${this.formData.clothes_id}/tags`,
          method: "POST",
          header: { "Content-Type": "application/json" },
          data: { tag },
        })

        // 检查响应状态
        if (response.statusCode === 200) {
          // 添加成功，更新本地数据
          this.formData.tags.push(tag)
          uni.showToast({ title: "标签添加成功", icon: "success", duration: 1000 })
        } else {
          uni.showToast({ title: "标签添加失败", icon: "none" })
          console.error("添加标签失败:", response)
        }
      } catch (error) {
        uni.showToast({ title: "网络请求失败", icon: "none" })
        console.error("添加标签请求错误:", error)
      }

      // 重置状态
      this.newTag = ""
      this.isAddingTag = false
    },

    // 修改后的删除标签方法
    async deleteTag(index, tag) {
      if (!tag) {
        tag = this.formData.tags[index]
      }

      try {
        // 调用后端API删除标签
        const response = await uni.request({
          url: `${setting.url}/api/clothes/${this.formData.clothes_id}/tags`,
          method: "DELETE",
          header: { "Content-Type": "application/json" },
          data: { tag },
        })

        // 检查响应状态
        if (response.statusCode === 200) {
          // 删除成功，更新本地数据
          this.formData.tags.splice(index, 1)
          uni.showToast({ title: "标签删除成功", icon: "success", duration: 1000 })
        } else {
          uni.showToast({ title: "标签删除失败", icon: "none" })
          console.error("删除标签失败:", response)
        }
      } catch (error) {
        uni.showToast({ title: "网络请求失败", icon: "none" })
        console.error("删除标签请求错误:", error)
      }
    },

    async saveClothesInfo() {
      if (!this.formData.category) {
        uni.showToast({ title: "请选择衣服大类", icon: "none" })
        return
      }

      if (!this.formData.subcategory) {
        uni.showToast({ title: "请选择详细类别", icon: "none" })
        return
      }

      try {
        uni.showLoading({ title: "保存中..." })

        const response = await uni.request({
          url: `${setting.url}/api/update_clothes`,
          method: "POST",
          header: { "Content-Type": "application/json" },
          data: {
            ...this.formData,
            clothes_id: this.formData.clothes_id,
          },
        })

        // 调试输出完整响应
        console.log("完整响应:", JSON.stringify(response, null, 2))

        if (response.statusCode === 200 && response.data.success) {
          uni.showToast({ title: "保存成功", icon: "success" })

          setTimeout(() => {
            uni.navigateTo({
            	url:`/pages/ClothesDetail/ClothesDetail?id=${this.formData.clothes_id}`
            })

            // 触发前页更新
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            if (prevPage && prevPage.loadClothesDetail) {
              prevPage.loadClothesDetail(this.formData.clothes_id) // 传递ID确保精准更新
            }
          }, 1500)
        }
      } catch (error) {
        console.error("网络请求异常:", error)
        uni.showToast({ title: "网络连接失败", icon: "none" })
      } finally {
        uni.hideLoading() // 确保隐藏加载提示
      }
    },
  },
}
</script>

<style scoped>
.edit-clothes {
  padding: 20rpx;
}

.form-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.image-upload {
  margin-bottom: 30rpx;
  text-align: center;
}

.preview-image {
  width: 300rpx;
  height: 300rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.upload-btn {
  background-color: #f5f5f5;
  color: #333;
  font-size: 26rpx;
  border-radius: 8rpx;
}

.form-item {
  margin-bottom: 25rpx;
  display: flex;
  align-items: center;
}

.form-item.tags-item {
  align-items: flex-start;
}

.label {
  width: 120rpx;
  font-size: 28rpx;
  color: #666;
}

input, .category-select {
  flex: 1;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 15rpx;
  font-size: 28rpx;
}

.category-select {
  color: #333;
}

.category-select.disabled {
  color: #999;
  background-color: #f5f5f5;
}

.tags-container {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}

.tag {
  display: flex;
  align-items: center;
  background-color: #f0f0f0;
  border-radius: 8rpx;
  padding: 8rpx 16rpx;
  margin: 0 10rpx 10rpx 0;
  font-size: 24rpx;
}

.delete-tag {
  margin-left: 8rpx;
  color: #ff4d4f;
  font-size: 24rpx;
}

.add-tag {
  background-color: #e0e0e0;
  border-radius: 8rpx;
  padding: 8rpx 16rpx;
  font-size: 24rpx;
  color: #666;
}

.tag-input {
  width: 100%;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 15rpx;
  font-size: 28rpx;
  margin-top: 10rpx;
}

.save-btn {
  margin-top: 40rpx;
  background-color: #FFF200;
  color: black;
  border: 1rpx solid black;
  border-radius: 10rpx;
  font-size: 28rpx;
}

/* 自定义选择器样式 */
.custom-picker {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1002;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

.custom-picker-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.custom-picker-content {
  width: 100%;
  max-height: 60vh;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
  z-index: 1003;
}

.picker-header {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eee;
  font-size: 32rpx;
}

.close-btn {
  font-size: 40rpx;
  padding: 10rpx 20rpx;
}

.picker-options {
  max-height: 50vh;
}

.picker-option {
  padding: 25rpx 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.picker-option.selected {
  color: #FFC90E;
  background-color: #fafafa;
}

.picker-option:active {
  background-color: #f0f0f0;
}
</style>

